<template>
  <div class="container mx-auto px-4 py-8">
    <!-- 页面标题 -->
    <div class="mb-8">
      <h1 class="text-3xl font-bold text-white mb-4">
        {{ pageTitle }}排行榜
      </h1>
      <!-- 类型切换 -->
      <div class="flex gap-4 mb-6">
        <el-button
          v-for="item in categories"
          :key="item.value"
          :type="currentType === item.value ? 'primary' : 'default'"
          @click="navigateTo(`/trending/${item.value}`)"
        >
          {{ item.label }}
        </el-button>
      </div>
      <!-- 时间范围切换 -->
      <div class="flex gap-2">
        <el-button
          v-for="range in timeRanges"
          :key="range.value"
          :type="selectedRange === range.value ? 'primary' : 'default'"
          size="small"
          @click="selectedRange = range.value; fetchTrendingList()"
        >
          {{ range.label }}
        </el-button>
      </div>
    </div>

    <!-- 排行榜列表 -->
    <div v-if="loading" class="space-y-4">
      <el-skeleton v-for="i in 10" :key="i" :rows="3" animated />
    </div>

    <div v-else class="space-y-4">
      <el-card
        v-for="(movie, index) in trendingList"
        :key="movie.movieId"
        class="ranking-card hover:shadow-lg transition-shadow"
      >
        <div class="flex gap-6">
          <!-- 排名 -->
          <div class="flex-shrink-0 w-16 text-center">
            <div
              class="text-3xl font-bold"
              :class="{
                'text-yellow-400': index === 0,
                'text-gray-400': index === 1,
                'text-orange-400': index === 2,
                'text-gray-500': index > 2
              }"
            >
              {{ index + 1 }}
            </div>
            <div class="text-xs text-gray-400 mt-1">
              <i
                v-if="movie.trend === 'up'"
                class="i-carbon-arrow-up text-green-500"
              ></i>
              <i
                v-else-if="movie.trend === 'down'"
                class="i-carbon-arrow-down text-red-500"
              ></i>
              <i v-else class="i-carbon-subtract text-gray-500"></i>
              <span class="ml-1">{{ movie.trendValue || '-' }}</span>
            </div>
          </div>

          <!-- 海报 -->
          <div class="flex-shrink-0">
            <el-image
              :src="movie.poster"
              :alt="movie.title"
              class="w-24 h-32 rounded cursor-pointer"
              fit="cover"
              @click="navigateTo(`/column/${currentType}/detail/${movie.movieId}`)"
            >
              <template #error>
                <div class="w-24 h-32 bg-gray-700 rounded flex items-center justify-center">
                  <el-icon :size="30" color="#999">
                    <Picture />
                  </el-icon>
                </div>
              </template>
            </el-image>
          </div>

          <!-- 信息 -->
          <div class="flex-1">
            <h3 class="text-xl font-semibold text-white mb-2">
              <NuxtLink
                :to="`/column/${currentType}/detail/${movie.movieId}`"
                class="hover:text-green-400 transition-colors"
              >
                {{ movie.title }}
              </NuxtLink>
            </h3>

            <div class="flex items-center gap-4 text-sm text-gray-400 mb-2">
              <span v-if="movie.rating" class="flex items-center">
                <el-icon class="mr-1" color="#F7BA2A">
                  <StarFilled />
                </el-icon>
                {{ movie.rating.toFixed(1) }}
              </span>
              <span>{{ movie.year }}</span>
              <span>{{ movie.country }}</span>
              <span>{{ movie.genre }}</span>
            </div>

            <p class="text-gray-400 text-sm line-clamp-2 mb-2">
              {{ movie.introduction }}
            </p>

            <div class="flex items-center gap-6 text-sm">
              <span class="text-gray-400">
                <i class="i-carbon-view mr-1"></i>
                播放量：<span class="text-white">{{ formatNumber(movie.viewCount || 0) }}</span>
              </span>
              <span class="text-gray-400">
                <i class="i-carbon-star mr-1"></i>
                收藏数：<span class="text-white">{{ formatNumber(movie.collectCount || 0) }}</span>
              </span>
              <span class="text-gray-400">
                <i class="i-carbon-chat mr-1"></i>
                评论数：<span class="text-white">{{ formatNumber(movie.commentCount || 0) }}</span>
              </span>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="flex-shrink-0 flex flex-col gap-2">
            <el-button
              type="primary"
              @click="navigateTo(`/column/${currentType}/detail/${movie.movieId}`)"
            >
              <i class="i-carbon-play mr-1"></i>
              立即播放
            </el-button>
            <el-button @click="handleCollection(movie)">
              <i class="i-carbon-star mr-1"></i>
              收藏
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 空状态 -->
    <el-empty v-if="!loading && trendingList.length === 0" description="暂无排行榜数据" />

    <!-- 分页 -->
    <div v-if="total > pageSize" class="mt-8 flex justify-center">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { StarFilled, Picture } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 当前类型
const currentType = computed(() => route.params.type as string || 'movie')

// 分类配置
const categories = [
  { label: '电影', value: 'movie' },
  { label: '电视剧', value: 'tv' },
  { label: '动漫', value: 'anime' },
  { label: '综艺', value: 'variety' }
]

// 时间范围
const timeRanges = [
  { label: '日榜', value: 'daily' },
  { label: '周榜', value: 'weekly' },
  { label: '月榜', value: 'monthly' },
  { label: '年榜', value: 'yearly' },
  { label: '总榜', value: 'total' }
]

// 页面标题
const pageTitle = computed(() => {
  const category = categories.find(c => c.value === currentType.value)
  return category ? category.label : '影视'
})

// 状态
const loading = ref(false)
const selectedRange = ref('weekly')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const trendingList = ref<any[]>([])

// 获取排行榜数据
const fetchTrendingList = async () => {
  loading.value = true
  try {
    const data = await $fetch('/dev-api/movie/basics/list', {
      headers: token.value ? {
        'Authorization': `Bearer ${userStore.token}`
      } : {},
      params: {
        columnValue: currentType.value,
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        orderBy: 'hottest', // 按热度排序
        timeRange: selectedRange.value
      }
    })

    if (data.code === 200) {
      trendingList.value = data.rows || []
      total.value = data.total || 0

      // 模拟趋势数据（实际项目中应该从后端获取）
      trendingList.value = trendingList.value.map((movie, index) => ({
        ...movie,
        trend: index < 3 ? 'up' : index < 6 ? '-' : 'down',
        trendValue: Math.floor(Math.random() * 10)
      }))
    }
  } catch (error) {
    console.error('获取排行榜失败:', error)
    // 使用模拟数据
    trendingList.value = generateMockData()
    total.value = 100
  } finally {
    loading.value = false
  }
}

// 生成模拟数据
const generateMockData = () => {
  const mockTitles = [
    '长津湖', '你好，李焕英', '流浪地球', '战狼2', '哪吒之魔童降世',
    '红海行动', '唐人街探案3', '复仇者联盟4', '速度与激情9', '阿凡达'
  ]

  return mockTitles.map((title, index) => ({
    movieId: index + 1,
    title,
    poster: `https://via.placeholder.com/200x300?text=${title}`,
    rating: 8.5 - index * 0.1,
    year: 2021 + Math.floor(Math.random() * 3),
    country: ['中国', '美国', '日本'][Math.floor(Math.random() * 3)],
    genre: ['动作', '喜剧', '科幻', '剧情'][Math.floor(Math.random() * 4)],
    introduction: `这是${title}的简介，这是一部非常精彩的影片，深受观众喜爱。`,
    viewCount: Math.floor(Math.random() * 10000000),
    collectCount: Math.floor(Math.random() * 100000),
    commentCount: Math.floor(Math.random() * 10000),
    trend: index < 3 ? 'up' : index < 6 ? '-' : 'down',
    trendValue: Math.floor(Math.random() * 10)
  }))
}

// 格式化数字
const formatNumber = (num: number) => {
  if (num >= 100000000) {
    return (num / 100000000).toFixed(1) + '亿'
  } else if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  }
  return num.toString()
}

// 处理收藏
const handleCollection = async (movie: any) => {
  if (!userStore.isLoggedIn) {
    router.push('/login')
    return
  }

  try {
    const data = await $fetch('/dev-api/member/collection/add', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      },
      body: {
        movieId: movie.movieId
      }
    })

    if (data.code === 200) {
      ElMessage.success('收藏成功')
    }
  } catch (error: any) {
    ElMessage.error(error.data?.msg || '收藏失败')
  }
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchTrendingList()
}

const handlePageChange = (val: number) => {
  currentPage.value = val
  fetchTrendingList()
}

// 监听路由变化
watch(() => route.params.type, () => {
  currentPage.value = 1
  fetchTrendingList()
})

// 初始化
onMounted(() => {
  fetchTrendingList()
})

// SEO设置
useSeoMeta({
  title: `${pageTitle.value}排行榜`,
  description: `查看最新最热的${pageTitle.value}排行榜`,
})
</script>

<style scoped>
.ranking-card {
  background-color: rgba(31, 41, 55, 0.8);
  border: 1px solid rgba(55, 65, 81, 0.5);
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-button--default) {
  background-color: transparent;
  border-color: rgba(55, 65, 81, 0.5);
  color: rgba(255, 255, 255, 0.8);
}

:deep(.el-button--default:hover) {
  background-color: rgba(55, 65, 81, 0.3);
  border-color: #409EFF;
  color: #409EFF;
}

:deep(.el-pagination) {
  --el-pagination-bg-color: transparent;
  --el-pagination-text-color: rgba(255, 255, 255, 0.8);
  --el-pagination-button-disabled-bg-color: rgba(31, 41, 55, 0.5);
  --el-pagination-button-disabled-color: rgba(255, 255, 255, 0.3);
  --el-pagination-hover-color: #409EFF;
}

:deep(.el-empty__description) {
  color: rgba(255, 255, 255, 0.6);
}
</style>